<template>
  <div class="family-outing">
    <div class="header">
      <h2>老人外出管理</h2>
      <el-button type="primary" @click="showApplyDialog = true">
        <el-icon><Plus /></el-icon>
        申请外出
      </el-button>
    </div>

    <!-- 外出申请列表 -->
    <div class="outing-list">
      <el-table :data="outingList" v-loading="loading">
        <el-table-column prop="elderName" label="老人姓名" width="120" />
        <el-table-column prop="outingReason" label="外出事由" width="200" />
        <el-table-column prop="startTime" label="开始时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.startTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="endTime" label="结束时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.endTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="destination" label="目的地" width="150" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button size="small" @click="viewOutingDetail(row)">
              查看详情
            </el-button>
            <el-button
                v-if="row.status === 'pending'"
                size="small"
                type="danger"
                @click="cancelOuting(row.applyId)"
            >
              取消申请
            </el-button>
            <el-button
                v-if="row.status === 'approved' && !row.actualReturnTime"
                size="small"
                type="warning"
                @click="openReturnDialog(row)"
            >
              销假
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 外出申请对话框 -->
    <el-dialog v-model="showApplyDialog" title="申请外出" width="600px">
      <el-form :model="applyForm" :rules="applyRules" ref="applyFormRef" label-width="100px">
        <el-form-item label="选择老人" prop="elderId">
          <el-select v-model="applyForm.elderId" placeholder="请选择老人" style="width: 100%">
            <el-option
                v-for="elder in familyElders"
                :key="elder.elderId"
                :label="elder.name"
                :value="elder.elderId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="外出事由" prop="outingReason">
          <el-input
              v-model="applyForm.outingReason"
              placeholder="请输入外出事由"
              type="textarea"
              :rows="3"
          />
        </el-form-item>
        <el-form-item label="目的地" prop="destination">
          <el-input v-model="applyForm.destination" placeholder="请输入目的地" />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
              v-model="applyForm.startTime"
              type="datetime"
              placeholder="选择开始时间"
              style="width: 100%"
              :disabled-date="disabledStartDate"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
              v-model="applyForm.endTime"
              type="datetime"
              placeholder="选择结束时间"
              style="width: 100%"
              :disabled-date="disabledEndDate"
          />
        </el-form-item>
        <el-form-item label="陪同人员" prop="companionInfo">
          <el-input
              v-model="applyForm.companionInfo"
              placeholder="请输入陪同人员信息"
              type="textarea"
              :rows="2"
          />
        </el-form-item>
        <el-form-item label="外出目的" prop="purpose">
          <el-input
              v-model="applyForm.purpose"
              placeholder="请输入详细的外出目的"
              type="textarea"
              :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showApplyDialog = false">取消</el-button>
        <el-button type="primary" @click="submitOutingApply" :loading="submitting">
          提交申请
        </el-button>
      </template>
    </el-dialog>

    <!-- 外出详情对话框 -->
    <el-dialog v-model="showDetailDialog" title="外出详情" width="500px">
      <div v-if="currentOuting" class="outing-detail">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="老人姓名">{{ currentOuting.elderName }}</el-descriptions-item>
          <el-descriptions-item label="外出事由">{{ currentOuting.outingReason }}</el-descriptions-item>
          <el-descriptions-item label="目的地">{{ currentOuting.destination }}</el-descriptions-item>
          <el-descriptions-item label="开始时间">{{ formatDateTime(currentOuting.startTime) }}</el-descriptions-item>
          <el-descriptions-item label="结束时间">{{ formatDateTime(currentOuting.endTime) }}</el-descriptions-item>
          <el-descriptions-item label="陪同人员">{{ currentOuting.companionInfo || '无' }}</el-descriptions-item>
          <el-descriptions-item label="外出目的">{{ currentOuting.purpose || '无' }}</el-descriptions-item>
          <el-descriptions-item label="申请状态">
            <el-tag :type="getStatusType(currentOuting.status)">
              {{ getStatusText(currentOuting.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="审批时间" v-if="currentOuting.approvalTime">
            {{ formatDateTime(currentOuting.approvalTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="实际返回时间" v-if="currentOuting.actualReturnTime">
            {{ formatDateTime(currentOuting.actualReturnTime) }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>

    <!-- 销假对话框 -->
    <el-dialog v-model="showReturnDialog" title="外出销假" width="400px">
      <el-form :model="returnForm" ref="returnFormRef" label-width="100px">
        <el-form-item label="实际返回时间" prop="actualReturnTime">
          <el-date-picker
              v-model="returnForm.actualReturnTime"
              type="datetime"
              placeholder="选择实际返回时间"
              style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="销假备注" prop="returnNotes">
          <el-input
              v-model="returnForm.returnNotes"
              placeholder="请输入销假备注（可选）"
              type="textarea"
              :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showReturnDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitReturn" :loading="submitting">
          确认销假
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getOutingRecords, applyOuting, cancelOutingApply, submitOutingReturn } from '@/api/outing'
import { getFamilyList } from '@/api/family'

/* ---------------- 数据 ---------------- */
const loading = ref(false)
const submitting = ref(false)
const showApplyDialog = ref(false)
const showDetailDialog = ref(false)
const showReturnDialog = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const outingList = ref([])
const familyElders = ref([])
const currentOuting = ref(null)
const applyFormRef = ref()
const returnFormRef = ref()

const applyForm = reactive({
  elderId: '',
  outingReason: '',
  destination: '',
  startTime: '',
  endTime: '',
  companionInfo: '',
  purpose: ''
})

const returnForm = reactive({
  applyId: '',
  actualReturnTime: '',
  returnNotes: ''
})

const applyRules = {
  elderId: [{ required: true, message: '请选择老人', trigger: 'change' }],
  outingReason: [{ required: true, message: '请输入外出事由', trigger: 'blur' }],
  destination: [{ required: true, message: '请输入目的地', trigger: 'blur' }],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }]
}

/* ---------------- 生命周期 ---------------- */
onMounted(() => {
  loadOutingRecords()
  loadFamilyElders()
})

/* ---------------- 方法 ---------------- */
async function loadOutingRecords() {
  try {
    loading.value = true
    const params = { 
      current: currentPage.value, 
      size: pageSize.value 
    }
    const response = await getOutingRecords(params)
    outingList.value = response.data.records || []
    total.value = response.data.total || 0
  } catch (e) {
    ElMessage.error('加载外出记录失败')
    console.error(e)
  } finally {
    loading.value = false
  }
}

async function loadFamilyElders() {
  try {
    const response = await getFamilyList({ current: 1, size: 100 })
    familyElders.value = response.data.records || []
  } catch (e) {
    console.error(e)
  }
}

async function submitOutingApply() {
  try {
    await applyFormRef.value.validate()
    submitting.value = true
    const formData = {
      ...applyForm,
      startTime: applyForm.startTime ? new Date(applyForm.startTime).toISOString() : '',
      endTime: applyForm.endTime ? new Date(applyForm.endTime).toISOString() : ''
    }
    await applyOuting(formData)
    ElMessage.success('外出申请提交成功')
    showApplyDialog.value = false
    resetApplyForm()
    loadOutingRecords()
  } catch (e) {
    if (e !== 'cancel') ElMessage.error('提交外出申请失败')
    console.error(e)
  } finally {
    submitting.value = false
  }
}

async function cancelOuting(applyId) {
  try {
    await ElMessageBox.confirm('确定要取消此外出申请吗？', '提示', { type: 'warning' })
    await cancelOutingApply(applyId)
    ElMessage.success('取消申请成功')
    loadOutingRecords()
  } catch (e) {
    if (e !== 'cancel') ElMessage.error('取消申请失败')
    console.error(e)
  }
}

/* ✅ 改名：消除重复声明 */
function openReturnDialog(outing) {
  currentOuting.value = outing
  returnForm.applyId = outing.applyId
  returnForm.actualReturnTime = new Date()
  returnForm.returnNotes = ''
  showReturnDialog.value = true
}

/* ✅ 销假提交逻辑 */
async function handleSubmitReturn() {
  try {
    submitting.value = true
    const formData = {
      ...returnForm,
      actualReturnTime: returnForm.actualReturnTime ? new Date(returnForm.actualReturnTime).toISOString() : ''
    }
    await submitOutingReturn(formData)
    ElMessage.success('销假成功')
    showReturnDialog.value = false
    loadOutingRecords()
  } catch (e) {
    ElMessage.error('销假失败')
    console.error(e)
  } finally {
    submitting.value = false
  }
}

function viewOutingDetail(outing) {
  currentOuting.value = outing
  showDetailDialog.value = true
}

function resetApplyForm() {
  Object.assign(applyForm, {
    elderId: '',
    outingReason: '',
    destination: '',
    startTime: '',
    endTime: '',
    companionInfo: '',
    purpose: ''
  })
}

function handleSizeChange(size) {
  pageSize.value = size
  currentPage.value = 1
  loadOutingRecords()
}

function handleCurrentChange(page) {
  currentPage.value = page
  loadOutingRecords()
}

function formatDateTime(dt) {
  return dt ? new Date(dt).toLocaleString('zh-CN') : '-'
}

function getStatusText(status) {
  const map = { pending: '待审批', approved: '已批准', rejected: '已拒绝', completed: '已完成', cancelled: '已取消' }
  return map[status] || status
}

function getStatusType(status) {
  const map = { pending: 'warning', approved: 'success', rejected: 'danger', completed: 'info', cancelled: 'info' }
  return map[status] || 'info'
}

function disabledStartDate(time) {
  return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
}

function disabledEndDate(time) {
  if (!applyForm.startTime) return time.getTime() < Date.now()
  return time.getTime() <= new Date(applyForm.startTime).getTime()
}
</script>

<style scoped>
.family-outing {
  padding: 20px;
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.outing-list {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
.outing-detail {
  line-height: 1.6;
}
</style>